
pacman::p_load(curl, data.table, tidyverse, scales)
if (Sys.info()[['user']] == "alal") {
  root = "/home/alal/Dropbox/1_Research/ElecAdminFunding/ElecAdminFundingReplication"
  theme_set(lal_plot_theme())
} else {
  root = "~/Dropbox/ElecAdminFunding/ElecAdminFundingReplication"
  theme_set(theme_minimal())
}

# Load NY Times COVID deat data
# Source: NY Times COVID-19 data repo: https://github.com/nytimes/covid-19-data
nytc = fread('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties-2020.csv')
nytc[, `:=` (date = as.Date(date), fips = sprintf('%05d', fips))]

# Load 2016 election data
# Source: https://github.com/tonmcg/US_County_Level_Election_Results_08-16
counties_res = fread('https://raw.githubusercontent.com/tonmcg/US_County_Level_Election_Results_08-20/master/2016_US_County_Level_Presidential_Results.csv')
us2016 = counties_res[, `:=` (fips = sprintf('%05d', combined_fips),
    result = fifelse(per_dem > per_gop, 'Clinton', 'Trump'))] %>%
  .[, .(fips, state_abbr, result)]

# Merge Covid and election data
us = nytc[us2016, on = 'fips', allow.cartesian = TRUE] %>%
  .[!is.na(date),
    lapply(.SD, sum, na.rm = TRUE), .SDcols = c('cases', 'deaths'),
    by = .(date, result)]

# Get daily Covid counts and percentages
us = us %>%
  group_by(result) %>%
  arrange(result, date) %>%
  mutate(daily_cases = cases - dplyr::lag(cases, 1),
    daily_deaths = deaths - dplyr::lag(deaths, 1)) %>%
  ungroup() %>%
  group_by(date) %>%
  mutate(daily_cases_perc = daily_cases/sum(daily_cases),
    daily_deaths_perc = daily_deaths/sum(daily_deaths)) %>%
  ungroup() %>%
  as.data.table()

# Make the plot
covid_plot = us[date>'2020-03-01' &date<'2020-11-05'] %>%
  mutate(result = ifelse(result=="Clinton", 
    " Supported Clinton in 2016", "Supported Trump in 2016")) %>%
  ggplot(aes(date, daily_cases_perc, col = result)) +
  geom_line(linewidth=1) +
  scale_color_brewer(palette = 'Set1', direction = -1) +
  scale_y_continuous(limits = c(0,1)) +
  theme(text = element_text(size=20, face="bold", color="black")) +
  theme(panel.grid.minor = element_blank()) +
  theme(legend.position = "bottom") +
  labs(y = "Share of Daily Reported COVID Cases", 
    x="Date", color = "")
ggsave(file.path(root, "output/covid_cases_partisan.pdf"), 
  covid_plot, width = 10, height = 8)

